package com.wecan.oauth.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wecan.api.saasdata.RoleData;
import com.wecan.api.saasdata.UserData;
import com.wecan.oauth.DTO.user.AddUserDTO;
import com.wecan.oauth.DTO.user.SelectUserPageDTO;
import com.wecan.oauth.DTO.user.UpdateUserDTO;
import com.wecan.base.PO.User;
import com.wecan.base.VO.UserVO;
import com.wecan.base.constants.PropertyConstants;
import com.wecan.base.controller.BaseController;
import com.wecan.base.model.Result;
import com.wecan.base.utils.AESUtil;
import com.wecan.cache.annotation.AccessLimit;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author liuzhihao
 * @Date 2022.01.20
 * @Version ${version}
 * @Description ${description}
 */
@RestController
@RequestMapping(value = "/user")
@Tag(name = "用户接口")
@Validated
public class UserController extends BaseController {

    @Autowired
    UserData userData;

    @Autowired
    RoleData roleData;

    @Value(PropertyConstants.ANNOTATION_APP_POSITION_SECRET)
    Long positionSecret;

    @Operation(summary = "用户信息", description = "用户信息",
            requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(content = @Content(mediaType = "application/json")),
            responses = {@ApiResponse(description = "用户信息", content = @Content(mediaType = "application/json"))})
    @AccessLimit
    @PostMapping(value = "/info")
    public Result getUserInfo() {
        Long userId = StpUtil.getLoginIdAsLong();
        User user = userData.queryUserById(userId);
        String roleIds = user.getRoleIds();
        List<Integer> userMarks;
        if (roleIds == null) {
            userMarks = new ArrayList<>();
        } else {
            List<Integer> roleList = JSONObject.parseArray(roleIds, Integer.class);
            userMarks = roleData.getUserMarks(roleList);
        }
        UserVO userVO = new UserVO();
        userVO.setId(user.getId());
        userVO.setToken(StpUtil.getTokenValue());
        userVO.setBirthday(user.getBirthday());
        userVO.setAvatar(user.getAvatar());
        userVO.setIntegral(user.getIntegral());
        userVO.setAvatar(user.getAvatar());
        userVO.setSex(user.getSex());
        userVO.setStatus(user.getStatus());
        userVO.setName(user.getName());
        userVO.setLevel(user.getLevel());
        userVO.setPositionId(user.getPositionId());
        userVO.setMarks(userMarks);
        return Result.content(userVO);
    }

    @Operation(summary = "修改用户信息", description = "修改用户信息",
            requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(content = @Content(mediaType = "application/json")),
            responses = {@ApiResponse(description = "修改用户信息", content = @Content(mediaType = "application/json"))})
    @Parameters({
            @Parameter(name = "updateUserDTO", required = true, description = "修改用户信息参数", schema = @Schema(implementation = UpdateUserDTO.class))
    })
    @AccessLimit(maxCount = 2)
    @SaCheckPermission("101010402")
    @PostMapping(value = "/update")
    public Result updateUser(@RequestBody @Valid UpdateUserDTO updateUserDTO) {
        User selectUser = userData.queryUserByPhone(updateUserDTO.getPhone());
        if (selectUser == null) {
            return Result.failure("用户不存在");
        }
        if (NumberUtils.compare(selectUser.getId(), updateUserDTO.getId()) != 0) {
            return Result.failure("用户信息错误");
        }
        User user = new User();
        BeanUtils.copyProperties(updateUserDTO, user);
        int rows = userData.updateById(user);
        return rows > 0 ? Result.success("用户信息修改成功") : Result.failure("用户信息修改失败");
    }

    @Operation(summary = "分页获取用户列表", description = "分页获取用户列表",
            requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(content = @Content(mediaType = "application/json")),
            responses = {@ApiResponse(description = "分页获取用户列表", content = @Content(mediaType = "application/json"))})
    @Parameters({
            @Parameter(name = "selectUserPageDTO", required = true, description = "分页获取用户列表参数", schema = @Schema(implementation = SelectUserPageDTO.class))
    })
    @AccessLimit
    @PostMapping(value = "/listpage")
    public Result<Page<User>> listUserInfo(@RequestBody @Valid SelectUserPageDTO selectUserPageDTO) {
        int pageNum = selectUserPageDTO.getPageNum();
        int pageSize = selectUserPageDTO.getPageSize();
        User user = new User();
        BeanUtils.copyProperties(selectUserPageDTO, user);
        Page<User> users = userData.selectPage(pageNum, pageSize, user);
        return Result.content(users);
    }

    @Operation(summary = "添加用户", description = "添加用户",
            requestBody = @io.swagger.v3.oas.annotations.parameters.RequestBody(content = @Content(mediaType = "application/json")),
            responses = {@ApiResponse(description = "添加用户", content = @Content(mediaType = "application/json"))})
    @Parameters({
            @Parameter(name = "addUserDTO", required = true, description = "添加用户参数", schema = @Schema(implementation = AddUserDTO.class))
    })
    @AccessLimit
    @PostMapping(value = "/add")
    public Result addUser(@RequestBody @Valid AddUserDTO addUserDTO) {
        String phone = addUserDTO.getPhone();
        User selectUser = userData.queryUserByPhone(phone);
        if (selectUser != null) {
            return Result.failure("手机号已经被注册");
        }
        String userId = AESUtil.generateUuid();
        User user = new User();
        if (StringUtils.isEmpty(addUserDTO.getName())) {
            user.setName("用户" + userId.substring(0, 12));
        } else {
            user.setName(addUserDTO.getName());
        }
        String password = AESUtil.encryptSqlField("12345678");
        user.setPhone(addUserDTO.getPhone());
        long phoneNumber = Long.parseLong(addUserDTO.getPhone());
        long positionId = phoneNumber + positionSecret;
        user.setPassword(password);
        user.setStatus(addUserDTO.getStatus());
        user.setSex(addUserDTO.getSex());
        user.setRoleIds(addUserDTO.getRoleIds());
        user.setPositionId(positionId);
        User insertUser = userData.insert(user);
        return insertUser != null ? Result.success("新增用户成功") : Result.failure("新增用户失败");
    }
}
